//
//  YZMConfirminforViewController.m
//  YZMicroStock
//
//  Created by apple on 16/11/4.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMConfirminforViewController.h"
#import "YZMConfirmiforTableViewCell.h"
#import "YZMWebViewService.h"
#import "YZMConfigureService.h"
#import "YZClient+TDTrade.h"
#import "YZGeneralResultModel.h"
#import "YZMStockViewController.h"
#import "YZMAlertView.h"
#import "NSNumber+Utils.h"

NSString *const confirmCell=@"YZMConfirmiforTableViewCell";

@interface YZMConfirminforViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic, strong) UITableView *listView;
@property(nonatomic, strong) NSArray *datasource;
@property(nonatomic, strong) NSString *moneyValueStr;
@property(nonatomic, strong) NSString *timeValueStr;
@property (nonatomic, strong) YZMTDConfigureModel *configureModel;
@property (nonatomic, strong) NSMutableDictionary *paramsDic;

@end

@implementation YZMConfirminforViewController

- (id)init {
    if (self = [super init]) {
        
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:YES];
    self.title = @"T+D点买A股";
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear: YES];
    self.title = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    [self createObject];
    self.navigationItem.rightBarButtonItem = [YZMAppStyle rightBarItemWithTitle:@"规则" target:self action:@selector(rightBarItemPressed:)];
    // Do any additional setup after loading the view.
}

- (void)rightBarItemPressed:(id)sender{
    
    [YZMWebViewService openTradeRule:YZM_TRADE_TYPE_FOR_A_STOCK_D];
}


-(void)createObject
{
    WS(ws)
    UIView *bottomBtnView = [UIView new];
    bottomBtnView.backgroundColor = [YZMAppStyle colorForLabelMark];
    [self.view addSubview:bottomBtnView];
    
    [bottomBtnView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.right.equalTo(ws.view);
        make.left.equalTo(ws.view);
    }];
    
    UIView *lineView = [YZMAppStyle splitLine];
    [bottomBtnView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.right.equalTo(bottomBtnView);
    }];
    
    self.listView=[[UITableView alloc]init];
    self.listView.backgroundColor=[YZMAppStyle appBackgroundColor];
    [self.view addSubview:_listView];
    _listView.separatorStyle=UITableViewCellSelectionStyleNone;
    [self.listView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(ws.view);
        make.bottom.equalTo(bottomBtnView.mas_top).offset(-5);
    }];
    [_listView registerClass:[YZMConfirmiforTableViewCell class] forCellReuseIdentifier:confirmCell];
    _listView.delegate=self;
    _listView.dataSource=self;
    
    [self createHeader];
    [self createFooter];
    
    UIButton *button=[YZMAppStyle submitButton];
    button.enabled = YES;
    button.backgroundColor=[YZMAppStyle colorForYellowButton];
    button.layer.borderWidth=0;
    [button setTitle:@"提交" forState:UIControlStateNormal];
    [button setTitleColor:[YZMAppStyle colorForMain] forState:UIControlStateNormal];
    [bottomBtnView addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(bottomBtnView).insets(UIEdgeInsetsMake(12, 15, 12, 15));
    }];
    [button addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)createHeader
{
    UIView *headerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 143)];
    _listView.tableHeaderView=headerView;

    UIView *backView=[[UIView alloc]initWithFrame:CGRectZero];
    backView.backgroundColor=[YZMAppStyle colorForMain];
    [headerView addSubview:backView];
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(headerView).offset(14);
        make.left.mas_equalTo(headerView);
        make.height.mas_equalTo(115);
        make.width.mas_equalTo(ScreenWidth);
    }];
    
    UILabel *confirmLabel=[YZMAppStyle labelWithWhite];
    confirmLabel.text=@"确认点买信息";
    [backView addSubview:confirmLabel];
    confirmLabel.font=[UIFont systemFontOfSize:16];
    [confirmLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(backView).offset(17);
        make.left.mas_equalTo(backView).offset(15);
        make.height.mas_equalTo(16);
    }];
    
    UIView *line1=[YZMAppStyle splitLine];
    [backView addSubview:line1];
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(confirmLabel.mas_bottom).offset(16);
        make.left.mas_equalTo(backView).offset(8);
        make.right.mas_equalTo(backView.mas_right).offset(-7);
    }];
    
    UIView *line2=[YZMAppStyle splitLine];
    [backView addSubview:line2];
    [line2 mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(line1.mas_bottom).offset(7);
        make.width.mas_equalTo(0.5);
        make.centerX.bottom.mas_equalTo(backView);
    }];
    
    UILabel *moneyValueLabel=[YZMAppStyle labelWithMediumBlack];
    [backView addSubview:moneyValueLabel];
    moneyValueLabel.textColor=[YZMAppStyle colorForRiseText];
    moneyValueLabel.text=self.moneyValueStr;
    moneyValueLabel.textAlignment=NSTextAlignmentCenter;
    moneyValueLabel.font=[UIFont boldSystemFontOfSize:24];
    [moneyValueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(line1).offset(9);
        make.width.mas_equalTo((ScreenWidth-1)/2);
        make.height.mas_equalTo(28);
    }];
    
    UILabel *moneyLabel=[YZMAppStyle labelWithSmallWhite];
    [backView addSubview:moneyLabel];
    moneyLabel.text=@"点买金额(元)";
    [moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(moneyValueLabel.mas_bottom).offset(2);
        make.centerX.mas_equalTo(moneyValueLabel);
        make.height.mas_equalTo(12);
    }];
    
    UILabel *timeValueLabel=[YZMAppStyle labelWithMediumBlack];
    [backView addSubview:timeValueLabel];
    timeValueLabel.textColor=[YZMAppStyle colorForRiseText];
    timeValueLabel.text=self.timeValueStr;
    timeValueLabel.textAlignment=NSTextAlignmentCenter;
    timeValueLabel.font=[UIFont boldSystemFontOfSize:24];
    [timeValueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(line1).offset(9);
        make.width.mas_equalTo((ScreenWidth-1)/2);
        make.left.mas_equalTo(line2);
        make.height.mas_equalTo(28);
    }];
    
    UILabel *timeLabel=[YZMAppStyle labelWithSmallWhite];
    [backView addSubview:timeLabel];
    timeLabel.text=@"合作期限(天)";
    [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(timeValueLabel.mas_bottom).offset(2);
        make.centerX.mas_equalTo(timeValueLabel);
        make.height.mas_equalTo(12);
    }];

}

-(void)createFooter
{
    UIView *footerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 150)];
    self.listView.tableFooterView=footerView;
    UILabel *explainLabel=[YZMAppStyle labelWithMediumGray];
    explainLabel.textColor=[YZMAppStyle colorForLightGrayText];
    [footerView addSubview:explainLabel];
    explainLabel.text=@"申请点买，即您已同意";
    [explainLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(footerView).offset(15);
        make.top.mas_equalTo(footerView).offset(21);
        make.height.mas_equalTo(14);
    }];
    
    UIButton *firstButton=[UIButton buttonWithType:UIButtonTypeCustom];
    firstButton.titleLabel.textAlignment = NSTextAlignmentLeft;
    [firstButton.titleLabel setFont:[UIFont systemFontOfSize:12]];
    [footerView addSubview:firstButton];
    [firstButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(explainLabel);
        make.top.mas_equalTo(explainLabel.mas_bottom).offset(12);
        make.height.mas_equalTo(14);
    }];
    [firstButton setTitle:@"《微策略点买人参与沪深A股交易合作涉及费用及资费标准》" forState:UIControlStateNormal];
    [firstButton setTitleColor:[YZMAppStyle colorForBlueText] forState:UIControlStateNormal];
    firstButton.tag=101;
    [firstButton addTarget:self action:@selector(getsomedelegate:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *secondButton=[UIButton buttonWithType:UIButtonTypeCustom];
    secondButton.titleLabel.textAlignment = NSTextAlignmentLeft;
    [secondButton.titleLabel setFont:[UIFont systemFontOfSize:12]];
    [footerView addSubview:secondButton];
    [secondButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(explainLabel);
        make.top.mas_equalTo(firstButton.mas_bottom);
        make.height.mas_equalTo(14);
    }];
    [secondButton setTitle:@"《微策略投资人与点买人参与沪深A股交易合作协议》" forState:UIControlStateNormal];
    [secondButton setTitleColor:[YZMAppStyle colorForBlueText] forState:UIControlStateNormal];
    secondButton.tag=102;
    [secondButton addTarget:self action:@selector(getsomedelegate:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton *thirdButton=[UIButton buttonWithType:UIButtonTypeCustom];
    thirdButton.titleLabel.textAlignment = NSTextAlignmentLeft;
    [thirdButton.titleLabel setFont:[UIFont systemFontOfSize:12]];
    [footerView addSubview:thirdButton];
    [thirdButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(explainLabel);
        make.top.mas_equalTo(secondButton.mas_bottom);
        make.height.mas_equalTo(14);
    }];
    [thirdButton setTitle:@"《微策略服务协议》" forState:UIControlStateNormal];
    [thirdButton setTitleColor:[YZMAppStyle colorForBlueText] forState:UIControlStateNormal];
    thirdButton.tag=103;
    [thirdButton addTarget:self action:@selector(getsomedelegate:) forControlEvents:UIControlEventTouchUpInside];
    
    if (iPhone4 || iPhone5 || !(iPhone6 || iPhone6P)) {
        
        [firstButton.titleLabel setFont:[UIFont systemFontOfSize:10]];
        [secondButton.titleLabel setFont:[UIFont systemFontOfSize:10]];
        [thirdButton.titleLabel setFont:[UIFont systemFontOfSize:10]];
    }
}

-(void)getsomedelegate:(UIButton *)sender
{
    if (sender.tag == 101) {
        
        [YZMWebViewService openFeeStandard:YZM_TRADE_TYPE_FOR_A_STOCK_D];
    } else if (sender.tag == 102) {
        
        [YZMWebViewService openCooperationDelegate];
    } else if (sender.tag == 103) {
        
        [YZMWebViewService openAgreementTradeDelegate];
    }
}


#pragma mark  --tableview

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _datasource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YZMConfirmiforTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:confirmCell forIndexPath:indexPath];
    
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.datasource=_datasource[indexPath.row];
    
    YZMIndexCount indexCount;
    indexCount.index = indexPath.row;
    indexCount.count = self.datasource.count;
    cell.indexCount = indexCount;
    cell.leftMargin = 10;
    cell.rightMargin = 10;
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 46;
}

-(void)submit:(UIButton *)sender {
    
    if (kNetworkNotReachability) {
        
        [MBProgressHUD showMessage:@"网络无法连接，请联网后重试"];
        return;
    }
    
    //判断余额是否足够
    double money = [@([self.paramsDic[@"principal"] doubleValue] + [self.paramsDic[@"deferCharge"] doubleValue] + self.configureModel.unHanldDeferCharge).r2fString doubleValue];
    
    double distanceMoney = money - [@(YZMUserServiceInstance.user.assets.balance).r2fString doubleValue];
    
    if ([@(distanceMoney) isGreaterThanDouble:0.0] ) {
        
        //余额不足
        YZMAlertView *alertView = [[YZMAlertView alloc] initWithFrame:self.view.frame];
        alertView.titleLabel.text = @"余额不足";
        alertView.titleLabel.textAlignment = NSTextAlignmentLeft;
        alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
        [alertView.sureButton setTitle:@"马上充值" forState:UIControlStateNormal];
        [alertView.cancelButton setTitle:@"暂不充值" forState:UIControlStateNormal];
        alertView.confirmHandle = ^{
            
            [YZMHCMInstance pushViewControllerWithName:@"recharge" andParams:@{YZBACKFLAG:@(YES)}];
            return YES;
        };
        
        if ([@(self.configureModel.unHanldDeferCharge) isGreaterThanDouble:0.0] ) {
            
            NSString *attStr = [NSString stringWithFormat:@"您在T+1账户历史策略未缴纳递延费共%@元,本次付款还差%@元！请充值后再发起T+D点买策略组",@(self.configureModel.unHanldDeferCharge).r2fString, @(distanceMoney).r2fString];
            NSMutableAttributedString *detailAttStr = [[NSMutableAttributedString alloc] initWithString:attStr];
            
            NSUInteger len = [attStr rangeOfString:@","].location - [attStr rangeOfString:@"共"].location - 2;
            [detailAttStr addAttribute:NSForegroundColorAttributeName value:[YZMAppStyle colorForRiseText] range:NSMakeRange([attStr rangeOfString:@"共"].location + 1,len)];
            NSUInteger lenT = [attStr rangeOfString:@"！"].location - [attStr rangeOfString:@"差"].location -2;
            [detailAttStr addAttribute:NSForegroundColorAttributeName value:[YZMAppStyle colorForRiseText] range:NSMakeRange([attStr rangeOfString:@"差"].location + 1,lenT)];

            alertView.contentLabel.attributedText = detailAttStr;
        }else{
            
            NSString *attStr = [NSString stringWithFormat:@"您的账户余额为%@元,本次付款还差%@元！请充值后再发起T+D点买策略组", @(YZMUserServiceInstance.user.assets.balance).r2fString, @(distanceMoney).r2fString];
            NSMutableAttributedString *detailAttStr = [[NSMutableAttributedString alloc] initWithString:attStr];
            
            NSUInteger len = [attStr rangeOfString:@","].location - [attStr rangeOfString:@"为"].location - 2;
            [detailAttStr addAttribute:NSForegroundColorAttributeName value:[YZMAppStyle colorForRiseText] range:NSMakeRange([attStr rangeOfString:@"为"].location + 1,len)];
            NSUInteger lenT = [attStr rangeOfString:@"！"].location - [attStr rangeOfString:@"差"].location -2;
            [detailAttStr addAttribute:NSForegroundColorAttributeName value:[YZMAppStyle colorForRiseText] range:NSMakeRange([attStr rangeOfString:@"差"].location + 1,lenT)];
            
            alertView.contentLabel.attributedText = detailAttStr;
        }
        
        [alertView showInView:self.navigationController.view];
        return;
    }

    //判断是否有递延费
    if ([@(self.configureModel.unHanldDeferCharge) isGreaterThanDouble:0.0]) {
        
        YZMAlertView *alertView = [[YZMAlertView alloc] initWithFrame:self.view.frame];
        alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
        alertView.confirmHandle = ^{
            
            [self submitStockBuyRequest];
            return YES;
        };
        
        
        NSString *attStr = [NSString stringWithFormat:@"您在T+1的账户历史策略未缴纳递延费共%@元，需缴纳后才能发起T+D点买策略组，确定支付吗？",@(self.configureModel.unHanldDeferCharge).r2fString];
        NSMutableAttributedString *detailAttStr = [[NSMutableAttributedString alloc] initWithString:attStr];
        
        NSUInteger len = [attStr rangeOfString:@"需"].location - [attStr rangeOfString:@"共"].location - 3;
        [detailAttStr addAttribute:NSForegroundColorAttributeName value:[YZMAppStyle colorForRiseText] range:NSMakeRange([attStr rangeOfString:@"共"].location + 1,len)];
        
        alertView.contentLabel.attributedText = detailAttStr;
        
        [alertView showInView:self.navigationController.view];
        return;
    }

    [self submitStockBuyRequest];
}

- (void)submitStockBuyRequest {

    MBProgressHUD *hud = [MBProgressHUD showMessageManual:@"提交中"];
    [YZClient td_createSchemeWithParams:self.paramsDic success:^(NSURLSessionDataTask *task, id responseObject) {
        
        [hud hide:YES];
        YZGeneralResultModel *topModel=responseObject;
        if (topModel.success) {
            
            [YZMUserServiceInstance fetchUserAssetsInfo];
            [MBProgressHUD showMessage:@"申请点买金额成功"];
            UIViewController *viewController = [YZMHCMInstance instanceWithControllerName:@"stockTD"];
            [YZMHCMInstance popViewController:viewController animated:YES];
        } else {
            
            NSString *token = [topModel.data objectForKey:@"token"];
            if (token.length >0) {
                
                self.configureModel.token = token;
            }
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        [hud hide:YES];
        [error yz_showMessage];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- init

- (void)updateWithParams:(NSDictionary *)params {
    
    self.configureModel = params[@"model"];
    double days = [params[@"positionDay"] doubleValue];
    double buyMoney = [params[@"buyMoney"] doubleValue];
    
    self.moneyValueStr = [NSString stringWithFormat:@"%@", @(buyMoney)];
    self.timeValueStr =[NSString stringWithFormat:@"%@", @(days)];;
    double bouns = floor(buyMoney / self.configureModel.leverValue);
    double deferCharge = floor(buyMoney * days / 10000 * self.configureModel.deferCharge);
    self.datasource = @[@[@"履约保证金(元)", @(bouns)],
                        @[@"递延费(元)",@(deferCharge)],
                        @[@"总共需要支付(元)",@(deferCharge + bouns)]];
    self.paramsDic = [NSMutableDictionary dictionaryWithCapacity:5];
    self.paramsDic[@"money"] = @(buyMoney);
    self.paramsDic[@"principal"] = @(bouns);
    self.paramsDic[@"deferCharge"] = @(deferCharge);
    self.paramsDic[@"holdDays"] = @(days);
    self.paramsDic[@"model"] = self.configureModel;
}

+ (instancetype)createWithParams:(NSDictionary *)params
{
    YZMConfirminforViewController *ctrl = [[self alloc] init];
    [ctrl updateWithParams: params];
    return ctrl;
}

@end
